<template>
  <div>
    <el-form
      ref="form"
      v-loading="loading"
      :model="form"
      :rules="rules"
      size="small"
      label-width="150px"
    >
      <el-form-item label="开启快递配送：" prop="status">
        <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
      </el-form-item>
      <div v-if="form.status">
        <el-form-item label="快递运费：" prop="freightType">
          <el-select v-model="form.freightType" placeholder="请选择">
            <el-option :value="0" label="商家包邮" />
            <el-option :value="1" label="买家承担运费" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.freightType===1" label="基础运费：" prop="freightFee">
          <el-input v-model.trim="form.freightFee" placeholder="请输入基础运费" maxlength="10">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="form.freightType===1" label="包邮策略：" prop="freeRule">
          <el-select v-model="form.freeRule" placeholder="请选择">
            <el-option :value="0" label="不包邮" />
            <el-option :value="1" label="按商品件数包邮" />
            <el-option :value="2" label="按订单金额包邮" />
          </el-select>
          <span v-if="form.freeRule===1||form.freeRule===2">&nbsp;订单包邮需要购买满&nbsp;</span>
          <el-form-item v-if="form.freeRule===1" class="app-display-i-b" prop="freeBaseNum">
            <el-input v-model="form.freeBaseNum" placeholder="请输入件数" maxlength="7">
              <template slot="append">件</template>
            </el-input>
          </el-form-item>
          <el-form-item v-if="form.freeRule===2" class="app-display-i-b" prop="freeBasePrice">
            <el-input v-model="form.freeBasePrice" placeholder="请输入金额" maxlength="10">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </el-form-item>
        <el-form-item label="开启备货时间：" prop="limitTime">
          <el-switch v-model="form.limitTime" />
          <div>开启后，顾客可在下单时选择发货时间</div>
        </el-form-item>
        <div v-if="form.limitTime">
          <el-form-item label="商品备货规则：" prop="prepayTimeUnit">
            <el-select v-model="form.prepayTimeUnit" placeholder="请选择">
              <el-option value="HOURS" label="按小时计算备货时间" />
              <el-option value="DAYS" label="按天计算备货时间" />
            </el-select>&nbsp;
            <el-form-item class="app-display-i-b" prop="prepayTime">
              <el-input v-model="form.prepayTime" placeholder="请输入" maxlength="3">
                <template slot="append">{{ form.prepayTimeUnit==='HOURS'?'小时':'天' }}</template>
              </el-input>
            </el-form-item>
          </el-form-item>
          <el-form-item label="可预约发货时间：" prop="bookingDays">
            <el-input v-model="form.bookingDays" placeholder="0代表24小时内" maxlength="2">
              <template slot="append">天</template>
            </el-input>
          </el-form-item>
        </div>
        <el-form-item label="订单取消规则：" prop="cancelRule">
          <el-select v-model="form.cancelRule" placeholder="请选择" style="width:250px">
            <el-option :value="1" label="支付后订单不可取消" />
            <el-option :value="0" label="支付后可免费取消订单" />
            <el-option :value="2" label="取消订单需要扣除违约金" />
          </el-select>
          <span v-if="form.cancelRule===2">&nbsp;违约金额为订单实付金额的&nbsp;</span>
          <el-form-item v-if="form.cancelRule===2" class="app-display-i-b" prop="cancelFeeRatio">
            <el-input v-model="form.cancelFeeRatio" placeholder="请输入">
              <template slot="append">%</template>
            </el-input>
          </el-form-item>
        </el-form-item>
        <el-form-item label="下单提示：" prop="remark">
          <el-input
            v-model="form.remark"
            :autosize="{ minRows: 2, maxRows: 6}"
            type="textarea"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </div>
      <el-form-item>
        <el-button type="primary" round @click="submit">保存配置</el-button>
        <el-button round @click="fetchData">重置配置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {
  getDeliveryConfig,
  saveDeliveryConfig
} from '@/views/wxaMallModule/api/delivery'
import {
  validateCustomTwoDecimal,
  validateCustomPositiveInt
} from '@/utils/validate.js'
import validatorMixin from './validatorMixin.js'
export default {
  mixins: [validatorMixin],
  props: {
    activeStore: {
      type: Object
    }
  },
  data() {
    // 校验方法
    // 运费
    const validatorFreightFee = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入基础运费'))
      } else if (!validateCustomTwoDecimal(value, 7)) {
        callback(new Error('请输入正整数，正小数（小数位不超过2位）'))
      } else {
        callback()
      }
    }
    // 数量
    const validatorFreeBaseNum = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入数量'))
      } else if (!validateCustomPositiveInt(value, 7)) {
        callback(new Error('请输入正整数'))
      } else {
        callback()
      }
    }
    // 金额
    const validatorFreeBasePrice = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入金额'))
      } else if (!validateCustomPositiveInt(value, 7)) {
        callback(new Error('请输入正整数，正小数（小数位不超过2位））'))
      } else {
        callback()
      }
    }

    const validatorCancelFeeRatio = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入'))
      } else if (!validateCustomPositiveInt(value, 2, [100])) {
        callback(new Error('请输入1~100'))
      } else {
        callback()
      }
    }

    return {
      // 校验字段
      rules: {
        freightType: [
          { required: true, message: '请选择', trigger: ['blur', 'change'] }
        ],
        freightFee: [
          {
            required: true,
            validator: validatorFreightFee,
            trigger: ['blur', 'change']
          }
        ],
        freeRule: [
          { required: true, message: '请选择', trigger: ['blur', 'change'] }
        ],
        freeBaseNum: [
          {
            required: true,
            validator: validatorFreeBaseNum,
            trigger: ['blur']
          }
        ],
        freeBasePrice: [
          {
            required: true,
            validator: validatorFreeBasePrice,
            trigger: ['blur']
          }
        ],
        cancelRule: [
          {
            required: true,
            message: '请选择',
            trigger: ['blur', 'change']
          }
        ],
        cancelFeeRatio: [
          {
            required: true,
            validator: validatorCancelFeeRatio,
            trigger: ['blur', 'change']
          }
        ]
      },
      // 配置

      // 状态
      loading: false,
      // 数据
      form: {
        status: 0,
        freightType: 0,
        freightFee: null,
        freeRule: 0,
        freeBaseNum: null,
        freeBasePrice: null,
        limitTime: false,
        bookingDays: 0,
        prepayTimeUnit: 'HOURS',
        prepayTime: null,
        remark: null,
        cancelRule: 1,
        cancelFeeRatio: null,
        type: 'EXPRESS'
      }
    }
  },
  computed: {},
  watch: {
    activeStore(newVal, oldVal) {
      if (newVal.storeId !== oldVal.storeId) {
        this.fetchData()
      }
    },
    'form.freeRule'(newVal, oldVal) {
      this.$nextTick(() => {
        this.$refs.form.clearValidate(['freeBaseNum', 'freeBasePrice'])
      })
    }
  },
  created() {},
  mounted() {
    this.fetchData()
  },
  methods: {
    /**
       * 数据组
       */
    // 获取数据
    fetchData() {
      this.loading = true
      getDeliveryConfig({ storeId: this.activeStore.storeId })
        .then((res) => {
          const data = res.data.express
          if (data) {
            data.freeBaseNum = null
            data.freeBasePrice = null
            if (data.freightType === 1) {
              data.freightFee = data.freightFee / 100
              if (data.freeRule === 1) {
                data.freeBaseNum = data.freeBase
              } else if (data.freeRule === 2) {
                data.freeBasePrice = data.freeBase / 100
              }
            }
            this.form = data
          } else {
            this.form = {
              status: 0,
              freightType: 0,
              freightFee: null,
              freeRule: 0,
              freeBaseNum: null,
              freeBasePrice: null,
              limitTime: false,
              prepayTimeUnit: 'HOURS',
              prepayTime: null,
              remark: null,
              cancelRule: 1,
              cancelFeeRatio: null,
              type: 'EXPRESS'
            }
          }
        })
        .catch((err) => {})
        .finally(() => {
          this.loading = false
        })
    },

    /**
       * 按钮组
       */
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let params = JSON.parse(JSON.stringify(this.form))
          if (params.status) {
            if (params.freightType === 0) {
              params.freightFee = null
              params.freeRule = 0
              params.freeBase = null
            } else {
              params.freightFee = this.$math.mul(params.freightFee, 100, 0) // 转化分;
              switch (params.freeRule) {
                case 0:
                  params.freeBase = null
                  break
                case 1:
                  params.freeBase = params.freeBaseNum
                  break
                case 2:
                  params.freeBase = this.$math.mul(
                    params.freeBasePrice,
                    100,
                    0
                  ) // 转化分;
                  break
              }
            }
            if (!params.limitTime) {
              params.prepayTimeUnit = null
              params.prepayTime = null
            }
            if (params.cancelRule !== 2) {
              params.cancelFeeRatio = null
            }
          } else {
            params = { status: 0, type: 'EXPRESS' }
          }
          params.storeId = params.storeId || this.activeStore.storeId

          this.loading = true
          saveDeliveryConfig(params)
            .then((res) => {
              this.$notify({
                title: '成功',
                message: '保存成功',
                type: 'success',
                duration: 2000,
                offset: 40
              })
            })
            .catch((err) => {})
            .finally(() => {
              this.loading = false
            })
        }
      })
    }

    /**
       * 状态组
       */

    /**
       * 方法组
       */
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  .el-textarea {
    width: 500px;
  }
  .el-input,
  .el-select {
    width: 200px;
  }
</style>
